import { LOAD_COUPON, COUPON_RESET, COUPON_SELECT } from '../constants/coupon'
import { asyncUserCoupon } from '../api/coupon'


// 设置用户的优惠券
export const setUserCoupon = data => {
  return {
    type: LOAD_COUPON,
    data
  }
}

// 选中券
export const selectCoupon = select_id => {
  return {
    type: COUPON_SELECT,
    select_id
  }
}

// 置用户的优惠券
export const resetUserCoupon = data => {
  return {
    type: COUPON_RESET,
    data
  }
}

// 异步获取优惠券
export const asyncGetUserCoupoon = (shop_only = false) => {
  return (dispatch, getState) => {
    const { token } = getState().user
    const { page } = getState().coupon
    const { shop_id } = getState().shop
    if (!token) return
    const nextPage = page + 1

    asyncUserCoupon(token, page, shop_only ? shop_id : null).then(({data, status}) => {
      console.log(data)
      if (status) {
        dispatch(setUserCoupon({
          list: data.data,
          page: nextPage,
          nomore: data.data.length < 5,
        }))
      }
    })
  }
}
